<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\WechatSubscribePush;
use App\Models\Studying;
use App\User;
use Illuminate\Support\Facades\Redis;
use App\Events\WxMessagePush;
use App\Contant\WxMessageType;
use App\Events\WxCustomerMessagePush;
class WechatRegisterUserPush extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wechat:register_user_push';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户注册消息推送，注册一小时后推送';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.s
     *
     * @return mixed
     */
    public function handle()
    {
        $pushCourse = Redis::get('push_course');
        return;
        if(!$pushCourse) {
            $pushCourse = WechatSubscribePush::first();
        }else{
            $pushCourse = json_decode($pushCourse);
        }
        if(!$pushCourse){
            return ;
        }
//        dd($pushCourse->id);
        $type = WxMessageType::IMAGE;
        $title = "【".WxMessageType::trans($type)."】".$pushCourse->title;
        $author = User::where('id',$pushCourse->user_id)->select('id','name')->first();
        $desc = $author->name . "[导师系列课]：\n" . "点击进入即可查看系列课内容\n回复[TD" . $pushCourse->id . "]不再接收该导师系列课推送";
        $data['type'] = $type;
        $data['list'] = [[
            "title"=>$title,
            "description"=>$desc,
            "url"=>env('PT_WEB_URL').'/course/detail/'.$pushCourse->id.'.html',
            "picurl"=>env('IMG_URL').$pushCourse->explain_url]
        ];
        logger()->info('推送数据');
        $userKeys = Redis::keys('subscribe_user_push*');
//        dd($userKeys);
        foreach($userKeys as $key){
            $userInfo = Redis::get($key);
            $user = json_decode($userInfo);

            if($user->subscribe == 0){
                continue;
            }
            $createTime = time()-strtotime($user->updated_at);
            if($createTime <= 5400 && $createTime >= 3600){
                $data['openid'] = $user->openid;
                $studying = new Studying();
                $studying->addOne($user->id, $pushCourse->id);

                event(new WxCustomerMessagePush($data));
                Redis::del('subscribe_user_push_'.$user->id);
            }
        }
    }
}
